<template>
  <div class="product-detail-page">
    <!-- 顶部导航栏 -->
    <Header />
    
    <div class="main-content">
      <div class="container">
        <!-- 面包屑导航 -->
        <div class="breadcrumb">
          <a-breadcrumb>
            <a-breadcrumb-item>
              <a @click="goHome">{{ $t('nav.home') }}</a>
            </a-breadcrumb-item>
            <a-breadcrumb-item>
              <a @click="goToProducts">{{ $t('nav.products') }}</a>
            </a-breadcrumb-item>
            <a-breadcrumb-item v-if="productDetail?.category">
              <a @click="goToCategory(productDetail.category)">{{ productDetail.category }}</a>
            </a-breadcrumb-item>
            <a-breadcrumb-item>{{ productDetail?.name || $t('product.productDetails') }}</a-breadcrumb-item>
          </a-breadcrumb>
        </div>
        
        <!-- 加载状态 -->
        <div v-if="loading" class="loading-container">
          <a-spin size="large" />
          <p>{{ $t('product.loadingDetails') || '正在加载商品详情...' }}</p>
        </div>
        
        <!-- 商品详情 -->
        <div v-else-if="productDetail" class="product-detail">
          <div class="product-content">
            <!-- 商品图片 -->
            <div class="product-gallery">
              <a-carousel v-model:current="currentImageIndex" dots-position="bottom">
                <div v-for="(image, index) in getProductImages()" :key="index">
                  <img :src="image" :alt="productDetail.name" class="product-image" />
                </div>
              </a-carousel>
              
              <!-- 缩略图 -->
              <div class="thumbnail-list">
                <div 
                  v-for="(image, index) in getProductImages()" 
                  :key="index"
                  class="thumbnail-item"
                  :class="{ active: currentImageIndex === index }"
                  @click="currentImageIndex = index"
                >
                  <img :src="image" :alt="productDetail.name" />
                </div>
              </div>
            </div>
            
            <!-- 商品信息 -->
            <div class="product-info">
              <h1 class="product-name">{{ productDetail.name }}</h1>
              
              <!-- 评分和评价 -->
              <div class="product-rating">
                <a-rate :value="productDetail.rating" disabled allow-half />
                <span class="rating-text">{{ productDetail.rating }}</span>
                <span class="review-count">({{ productDetail.reviews }}条评价)</span>
              </div>
              
              <!-- 价格信息 -->
              <div class="product-price">
                <span class="current-price">¥{{ productDetail.price }}</span>
                <span v-if="productDetail.originalPrice > productDetail.price" class="original-price">
                  ¥{{ productDetail.originalPrice }}
                </span>
                <span class="discount-tag" v-if="productDetail.originalPrice > productDetail.price">
                  {{ Math.round((1 - productDetail.price / productDetail.originalPrice) * 100) }}% OFF
                </span>
              </div>
              
              <!-- 商品描述 -->
              <div class="product-description">
                <p>{{ productDetail.description }}</p>
              </div>
              
              <!-- 规格选择 -->
              <div class="product-specs" v-if="productDetail.specifications">
                <h3>{{ $t('product.specifications') }}</h3>
                <div class="spec-list">
                  <div 
                    v-for="(value, key) in productDetail.specifications" 
                    :key="key"
                    class="spec-item"
                  >
                    <span class="spec-label">{{ key }}：</span>
                    <span class="spec-value">{{ value }}</span>
                  </div>
                </div>
              </div>
              
              <!-- 购买数量 -->
              <div class="quantity-selector">
                <span class="quantity-label">{{ $t('product.quantity') }}：</span>
                <a-input-number
                  v-model:value="quantity"
                  :min="1"
                  :max="productDetail.stock"
                  size="large"
                />
                <span class="stock-info">库存：{{ productDetail.stock }}件</span>
              </div>
              
              <!-- 操作按钮 -->
              <div class="product-actions">
                <a-button 
                  type="primary" 
                  size="large"
                  :disabled="productDetail.stock <= 0"
                  @click="addToCart"
                >
                  <ShoppingCartOutlined />
                  加入购物车
                </a-button>
                <a-button 
                  size="large"
                  :disabled="productDetail.stock <= 0"
                  @click="buyNow"
                >
                  立即购买
                </a-button>
                <a-button 
                  size="large"
                  @click="toggleFavorite"
                >
                  <HeartOutlined v-if="!isFavorite" />
                  <HeartFilled v-else style="color: #ff4d4f" />
                  {{ isFavorite ? '已收藏' : '收藏' }}
                </a-button>
              </div>
              
              <!-- 商品特色 -->
              <div class="product-features" v-if="productDetail.features">
                <h3>商品特色</h3>
                <ul class="feature-list">
                  <li v-for="feature in productDetail.features" :key="feature">
                    {{ feature }}
                  </li>
                </ul>
              </div>
            </div>
          </div>
          
          <!-- 商品详情标签页 -->
          <div class="product-tabs">
            <a-tabs v-model:activeKey="activeTab">
              <a-tab-pane key="detail" tab="{{ $t('product.productDetails') }}">
                <div class="tab-content">
                  <h3>{{ $t('product.productDetails') }}</h3>
                  <p>{{ productDetail.description }}</p>
                  <!-- 这里可以添加更详细的商品信息 -->
                </div>
              </a-tab-pane>
              <a-tab-pane key="specs" tab="{{ $t('product.specifications') }}">
                <div class="tab-content">
                  <h3>{{ $t('product.specifications') }}</h3>
                  <div class="specs-table">
                    <div 
                      v-for="(value, key) in productDetail.specifications" 
                      :key="key"
                      class="spec-row"
                    >
                      <span class="spec-key">{{ key }}</span>
                      <span class="spec-value">{{ value }}</span>
                    </div>
                  </div>
                </div>
              </a-tab-pane>
              <a-tab-pane key="reviews" tab="{{ $t('product.reviews') }}">
                <div class="tab-content">
                  <h3>{{ $t('product.reviews') }}</h3>
                  <p>暂无评价</p>
                </div>
              </a-tab-pane>
            </a-tabs>
          </div>
        </div>
        
        <!-- 商品不存在 -->
        <div v-else class="not-found">
          <ExclamationCircleOutlined class="not-found-icon" />
          <h3>商品不存在</h3>
          <p>该商品可能已下架或不存在</p>
          <a-button type="primary" @click="goToProducts">
            返回商品列表
          </a-button>
        </div>
      </div>
    </div>
    
    <!-- 底部信息 -->
    <Footer />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
import { message } from 'ant-design-vue'
import {
  ShoppingCartOutlined,
  HeartOutlined,
  HeartFilled,
  ExclamationCircleOutlined
} from '@ant-design/icons-vue'
import Header from '@/components/Header.vue'
import Footer from '@/components/Footer.vue'
import { favoriteApi } from '@/api'

// 使用Vuex store和Vue Router
const store = useStore()
const router = useRouter()
const route = useRoute()

// 响应式数据
const loading = ref(false)
const currentImageIndex = ref(0)
const quantity = ref(1)
const activeTab = ref('detail')
const isFavorite = ref(false)

// 计算属性
const productDetail = computed(() => store.getters['product/productDetail'])

// 方法
const getProductImages = () => {
  console.log('getProductImages 被调用，productDetail:', productDetail.value)
  
  if (!productDetail.value) {
    console.log('productDetail 为空，返回默认图片')
    return ['https://picsum.photos/400/400?random=999']
  }
  
  // 如果商品有images数组，使用images
  if (productDetail.value.images && productDetail.value.images.length > 0) {
    console.log('使用 images 数组:', productDetail.value.images)
    return productDetail.value.images
  }
  
  // 如果商品有image字段，使用image作为单张图片
  if (productDetail.value.image) {
    console.log('使用 image 字段:', productDetail.value.image)
    return [productDetail.value.image]
  }
  
  // 默认图片
  console.log('使用默认图片')
  return ['https://picsum.photos/400/400?random=999']
}

const loadProductDetail = async () => {
  const productId = route.params.id
  if (!productId) return
  
  loading.value = true
  
  try {
    console.log('开始加载商品详情，ID:', productId)
    const result = await store.dispatch('product/fetchProductDetail', productId)
    console.log('商品详情加载结果:', result)
    console.log('当前商品详情:', productDetail.value)
    
    // 检查收藏状态
    await checkFavoriteStatus(productId)
  } catch (error) {
    console.error('加载商品详情失败:', error)
    message.error('加载商品详情失败，请重试')
  } finally {
    loading.value = false
  }
}

const checkFavoriteStatus = async (productId) => {
  try {
    const response = await favoriteApi.checkFavorite(productId)
    if (response.code === 200) {
      isFavorite.value = response.data.isFavorite
    }
  } catch (error) {
    console.error('检查收藏状态失败:', error)
  }
}

const addToCart = () => {
  if (productDetail.value.stock <= 0) {
    message.warning('该商品暂时缺货')
    return
  }
  
  store.dispatch('cart/addToCart', {
    ...productDetail.value,
    quantity: quantity.value
  })
  
  message.success('已添加到购物车')
}

const buyNow = () => {
  if (productDetail.value.stock <= 0) {
    message.warning('该商品暂时缺货')
    return
  }
  
  // 清空购物车并添加当前商品
  store.dispatch('cart/clearCart')
  store.dispatch('cart/addToCart', {
    ...productDetail.value,
    quantity: quantity.value
  })
  
  // 跳转到结算页面
  router.push('/checkout')
}

const toggleFavorite = async () => {
  try {
    if (isFavorite.value) {
      // 取消收藏
      const response = await favoriteApi.removeFavorite(productDetail.value.id)
      if (response.code === 200) {
        isFavorite.value = false
        message.success('已取消收藏')
      } else {
        message.error(response.message || '取消收藏失败')
      }
    } else {
      // 添加收藏
      const response = await favoriteApi.addFavorite(productDetail.value.id)
      if (response.code === 200) {
        isFavorite.value = true
        message.success('已添加到收藏')
      } else {
        message.error(response.message || '添加收藏失败')
      }
    }
  } catch (error) {
    console.error('收藏操作失败:', error)
    message.error('操作失败，请重试')
  }
}

const goHome = () => {
  router.push('/')
}

const goToProducts = () => {
  router.push('/products')
}

const goToCategory = (category) => {
  router.push(`/category/${category}`)
}

// 监听路由参数变化
watch(() => route.params.id, (newId) => {
  if (newId) {
    loadProductDetail()
  }
})

// 生命周期
onMounted(() => {
  loadProductDetail()
})
</script>

<style scoped>
.product-detail-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.main-content {
  flex: 1;
  padding: 20px 0;
}

.breadcrumb {
  background: white;
  padding: 15px 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.loading-container p {
  margin-top: 15px;
  color: #666;
}

.product-detail {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.product-content {
  display: grid;
  grid-template-columns: minmax(400px, 1fr) 1fr;
  gap: 40px;
  padding: 40px;
}

.product-gallery {
  display: flex;
  flex-direction: column;
  gap: 20px;
  min-width: 400px;
  flex-shrink: 0;
}

.product-image {
  width: 100%;
  min-width: 400px;
  height: 400px;
  object-fit: cover;
  border-radius: 8px;
}

.thumbnail-list {
  display: flex;
  gap: 10px;
  justify-content: center;
  flex-wrap: wrap;
  min-height: 80px;
}

.thumbnail-item {
  width: 80px;
  min-width: 80px;
  height: 80px;
  border: 2px solid #f0f0f0;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
  overflow: hidden;
  flex-shrink: 0;
}

.thumbnail-item:hover,
.thumbnail-item.active {
  border-color: #1890ff;
}

.thumbnail-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-info {
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.product-name {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin: 0;
  line-height: 1.4;
}

.product-rating {
  display: flex;
  align-items: center;
  gap: 10px;
}

.rating-text {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.review-count {
  font-size: 14px;
  color: #666;
}

.product-price {
  display: flex;
  align-items: center;
  gap: 15px;
}

.current-price {
  font-size: 28px;
  font-weight: bold;
  color: #ff4d4f;
}

.original-price {
  font-size: 16px;
  color: #999;
  text-decoration: line-through;
}

.discount-tag {
  background: #ff4d4f;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.product-description {
  color: #666;
  line-height: 1.6;
}

.product-specs h3,
.product-features h3 {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0 0 15px 0;
}

.spec-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.spec-item {
  display: flex;
  gap: 10px;
}

.spec-label {
  font-weight: 500;
  color: #333;
  min-width: 80px;
}

.spec-value {
  color: #666;
}

.quantity-selector {
  display: flex;
  align-items: center;
  gap: 15px;
}

.quantity-label {
  font-weight: 500;
  color: #333;
}

.stock-info {
  font-size: 14px;
  color: #666;
}

.product-actions {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.product-actions .ant-btn {
  flex: 1;
  min-width: 120px;
}

.feature-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.feature-list li {
  padding: 8px 0;
  color: #666;
  position: relative;
  padding-left: 20px;
}

.feature-list li::before {
  content: '✓';
  position: absolute;
  left: 0;
  color: #52c41a;
  font-weight: bold;
}

.product-tabs {
  padding: 0 40px 40px;
}

.tab-content {
  padding: 20px 0;
}

.tab-content h3 {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0 0 20px 0;
}

.specs-table {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.spec-row {
  display: flex;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.spec-row:last-child {
  border-bottom: none;
}

.spec-key {
  font-weight: 500;
  color: #333;
  min-width: 120px;
}

.spec-value {
  color: #666;
  flex: 1;
}

.not-found {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  text-align: center;
}

.not-found-icon {
  font-size: 64px;
  color: #d9d9d9;
  margin-bottom: 20px;
}

.not-found h3 {
  font-size: 20px;
  color: #333;
  margin: 0 0 10px 0;
}

.not-found p {
  color: #666;
  margin: 0 0 20px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .main-content {
    padding: 15px 0;
  }
  
  .product-content {
    grid-template-columns: 1fr;
    gap: 20px;
    padding: 20px;
  }
  
  .product-gallery {
    min-width: auto;
  }
  
  .product-image {
    height: 300px;
    min-width: auto;
  }
  
  .thumbnail-list {
    flex-wrap: wrap;
  }
  
  .product-name {
    font-size: 20px;
  }
  
  .current-price {
    font-size: 24px;
  }
  
  .product-actions {
    flex-direction: column;
  }
  
  .product-actions .ant-btn {
    width: 100%;
  }
  
  .product-tabs {
    padding: 0 20px 20px;
  }
  
  .spec-row {
    flex-direction: column;
    gap: 5px;
  }
  
  .spec-key {
    min-width: auto;
  }
}
</style> 